﻿using Kinlo.MESDocking;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
using UIWindows.GlobalStatics;
using UIWindows.Models.Devices;
using XingLucifer.Devices;
using Kinlo.Entitys;
using System.Reflection;
using UIWindows.Tools.Helper;
using NPOI.SS.Formula.Functions;
using XingLucifer.IBase.Enums;
using UIWindows.Views;
using System.Collections.ObjectModel;
using UIWindows.Models.ParameterModels;
using UIWindows.Services;
using UIWindows.Models;
using Microsoft.AspNetCore.Http;

namespace UIWindows.Services.PLC_MESHelper
{
    /// <summary>
    /// 工艺参数上传MES类
    /// </summary>
    public class ProcessParameterUploadHelper : HelperBase
    {

        PLCBase InjMachine { get; set; }
        //MESCollectionItemsParameterModel parameter { get; set; }

        MESUserNameCheck mesUserInteraction { get; set; }

        ObservableCollection<MesOutputParameterModel> _mesParameter { get; set; }

        MESProcessParameter _mesProcessParameter { get; set; }
        public ProcessParameterUploadHelper(
            DeviceInteractiveaddressStatic deviceInteractiveaddressStatic,
            DeviceClientModel deviceModel,
            TemporaryStatic temporaryStatic,
            ParameterStatic parameterStatic,
            DeviceConfigStatic deviceConfigStatic,
            SystemConfigStatic systemConfigStatic,
             HomeStatic homeStatic,
             Action<string, string, string, string, string, long, DateTime, string, string, string, string> log, Action<string, string, string> dialog
            ) : base(deviceInteractiveaddressStatic, deviceModel, temporaryStatic, parameterStatic, deviceConfigStatic, systemConfigStatic, homeStatic, log, dialog)
        {
            InjMachine =  deviceModel.PLC;
            mesUserInteraction = new MESUserNameCheck(_log, _dialog, machineInfo_Type);
            var machineInfoType = (MachineInfoTypes)Enum.Parse(typeof(MachineInfoTypes), deviceModel.ServiceName);
            if (_deviceInteractiveaddressStatic.MesOutputParameters != null && _deviceInteractiveaddressStatic.MesOutputParameters.ContainsKey(machineInfoType))
            {
                _mesParameter = _deviceInteractiveaddressStatic.MesOutputParameters[machineInfoType];
            }
           

            _mesProcessParameter = new MESProcessParameter(_log, _dialog, machineInfo_Type);
        }
        public override Task Handle()
        {
            ProcessParameterUpload();
            return base.Handle();
        }
        public void ProcessParameterUpload()
        {
            //if (_mesParameterStatic.MesOutputParameters != null && _mesParameterStatic.MesOutputParameters.Count > 0)
            //{

            //}

            //if (_parameter.MachineStatus != "1") return;
            try
            {
                if (_mesParameter != null && _mesParameter.Count > 0)
                {

                    //var entityType = GetEntityType();
                    //var entity = CreateEntityType<object>();

                    //// 设置数据库表名
                    //PropertyInfo tableNameProperty = entityType.Item2.GetProperty("TableName", BindingFlags.Static | BindingFlags.Public);
                    //tableNameProperty.SetValue(entity, Convert.ChangeType($"{entityType.Item1.Name}_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}", tableNameProperty.PropertyType), null);
                    //MachineInfoTypes machineInfoType = (MachineInfoTypes)Enum.Parse(typeof(MachineInfoTypes), _deviceModel.ServiceName);
                    //object entityData = null;


                    var entityType = GetEntityType();
                    var entity = CreateEntityType<object>();

                    // 设置数据库表名
                    PropertyInfo tableNameProperty = entityType.Item2.GetProperty("TableName", BindingFlags.Static | BindingFlags.Public);
                    tableNameProperty.SetValue(entity, Convert.ChangeType($"{entityType.Item1.Name}_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}", tableNameProperty.PropertyType), null);

                    if (_collectParamete != null && _collectParamete.Count > 0)
                    {

                        #region 采集工艺参数
                        ProcessParameters(entity, InjMachine);
                        #endregion

                        #region 读取焊机数据
                        ProcessSpotWelderData(entity);
                        #endregion

                        #region 读取短路测试仪数据
                        ProcesscircuitTester(entity);
                        #endregion

                        #region 读取白班OR夜班NG分类
                        ProcessClassNGType(entity, InjMachine);
                        #endregion
                    }








                    Dictionary<string, object> mesParam = new Dictionary<string, object>
                    {
                        { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                    };
                    var mesParameters = new Dictionary<string, object>();

                    foreach (var item in _mesParameter)
                    {

                        if(item.IsEnable)
                        {
                            try
                            {
                                var valueType = GetTypeByStringHelper.GetTypeByString(item.DataType);
                                if (item.Description == null || string.IsNullOrEmpty(item.Description) ||
                                    item.PropertyName == null || string.IsNullOrEmpty(item.PropertyName))
                                {
                                    //找不到这个电池的参数
                                }
                                else
                                {
                                    var propertyInfo = entity.GetType().GetProperty(item.PropertyName, BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                                    //var ret = propertyInfos.Where(x => x.Name == item.PropertyName).FirstOrDefault();                       
                                    if (propertyInfo != null) //如果电池中有此参数
                                    {
                                        //取出值
                                        var value = propertyInfo.GetValue(entity, null);
                                        if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
                                        {
                                            value = "0";
                                        }
                                        if(item.DataType=="DateTime")
                                        {
                                            string inputFormat = "yyyy/MM/dd HH:mm:ss"; // 输入的格式
                                            string outputFormat = "yyyy-MM-dd HH:mm:ss"; // 输出的格式

                                            DateTime dateTime;
                                            if (DateTime.TryParseExact(value.ToString(), inputFormat, null, System.Globalization.DateTimeStyles.None, out dateTime))
                                            {
                                                value = dateTime.ToString(outputFormat);
                                            }
                                        }
                                        mesParameters.TryAdd(item.TechnicsParamCode, value);
                                    }

                                }
                            }catch(Exception ex)
                            {
                                Console.WriteLine(ex.ToString());
                            }
                           

                        }
                        //parameter.TryAdd("produceParamEntityList", produceInEntityList);
                    }


                    if(mesParameters.Count==0)
                    {
                        return;
                    }
                    mesParam.Add("parameter", mesParameters);

                    var result = _mesProcessParameter.MESInteraction(_parameterStatic.MESParameter.EquipUploadParamRoute,
                         _parameterStatic.MESParameter.EquipUploadParamTime,
                         1, DateTime.Now, mesParam);

                }
            }
            catch (Exception ex)
            {
                RunLog($"工艺参数上传报错：{ex}");
            }
           


            //var latestData = ProductionData.FindAll(null, "SnowflakeId DESC", null, 0, 1);

        }



    }
}
